package ru.nsu.expertsystem.chucknorris;

import org.drools.definition.rule.Rule;
import org.drools.event.rule.ObjectInsertedEvent;
import org.drools.event.rule.ObjectRetractedEvent;
import org.drools.event.rule.ObjectUpdatedEvent;
import org.drools.event.rule.WorkingMemoryEvent;
import org.drools.event.rule.WorkingMemoryEventListener;
import org.drools.runtime.rule.PropagationContext;

public class LoggingWorkerMemoryEventListener implements WorkingMemoryEventListener {

	@Override
	public void objectInserted(ObjectInsertedEvent e) {
		String ruleMessage = getRuleMessage(e);
		
		System.out.println("+: " + e.getObject() + ruleMessage);
	}

	@Override
	public void objectRetracted(ObjectRetractedEvent e) {
		String ruleMessage = getRuleMessage(e);
		
		System.out.println("-: " + e.getOldObject() + ruleMessage);
	}
	
	@Override
	public void objectUpdated(ObjectUpdatedEvent e) {
		String ruleMessage = getRuleMessage(e);
		
		System.out.println("*: " + e.getOldObject() + " -> " + e.getObject() + ruleMessage);
	}
	
	private String getRuleMessage(WorkingMemoryEvent e) {
		PropagationContext context = e.getPropagationContext();
		
		if (context != null && e.getPropagationContext().getRule() != null) {
			Rule rule = context.getRule();
			
			if (rule != null) {
				return " (" + rule.getName() + ")";
			}
		}

		return "";
	}

}
